from fastapi import APIRouter, Query
import typing as t

from server.module_chat.chat.core.agent.agent import Agent
from server.settings import Settings
from server.utils.response_util import ResponseUtil

agentController = APIRouter(prefix="/agent", tags=["Agent接口"])


@agentController.get("/get_agents", summary="获取agent列表")
async def get_agents():
    agents: t.List[Agent] = Settings.agent_settings.AGENTS_CONFIG
    agents_dict = [filter_none(agent.dict(by_alias=True)) for agent in agents]
    return ResponseUtil.success(data=agents_dict)


@agentController.get("/get_agent", summary="获取agent信息")
async def get_agent(id: str = Query(..., description="Agent ID")):
    agents: t.List[Agent] = Settings.agent_settings.AGENTS_CONFIG
    for agent in agents:
        if agent.id == id:
            agent_dict = filter_none(agent.dict(by_alias=True))
            return ResponseUtil.success(data=agent_dict)
    return ResponseUtil.success()


def filter_none(d):
    """ 递归地从字典中删除值为 None 的项 """
    if not isinstance(d, dict):
        if isinstance(d, list):
            return [filter_none(item) for item in d]
        return d
    return {k: filter_none(v) for k, v in d.items() if v is not None}
